import logging
from flask import current_app, jsonify

from flask import render_template
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.response_code import RET
from . import index_blu

@index_blu.route("/news_list")
def get_news_list():
    """
    根据分类ID获取新闻咨询列表
    """

    #1. 获取参数[cid,当前页码,分页数据量]
    cid = request.args.get("cid")
    page = request.args.get("page",1)
    per_page = request.args.get("per_page",constants.HOME_PAGE_MAX_NEWS)

    #2.校验参数
    if not cid:
        return jsonify(errno=RET.DATAERR,errmsg="缺少参数")

    #3.获取数据
    try:
        #如果查询的是"最新"的新闻咨询,则获取的必须是所有分类下的信息
        filters =[]
        if cid !="1":
            filters.append(News.category_id==cid)
        pagination =News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg="无效参数")

    page = pagination.page
    #获取当前页面中的所有的数据,是一个list数据,成员是news模型对象
    news_list = pagination.items
    pages = pagination.pages

    #数据重构[把数据的格式进行调整为我们需要的]
    news_li = []
    for news in news_list:
        news_li.append(news.to_basic_dict())

    #4.返回数据
    return jsonify(errno=RET.OK,errmsg="OK",cid=cid,current_page=page,pages=pages,news_list=news_li)




@index_blu.route("/")
def index():
    #查看当前已经登录的用户

    user_id = session.get("user_id")

    #用户默认没有登录
    user = None

    if user_id:
        #根据user_id到数据库中查询用户信息
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    #查询点击排行的咨询列表
    news_list = None

    try:
        new_list =News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    #获取新闻咨询的分类信息
    categories = Category.query.all()

    return render_template('news/index.html',
                           user=user,
                           new_list=news_list,
                           categories=categories)

@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file("news/favicon.ico")
